package com.bdqn.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.common.utils.PageUtils;
import com.bdqn.common.utils.Query;
import com.bdqn.common.utils.R;
import com.bdqn.gulimall.ware.dao.WareInfoDao;
import com.bdqn.gulimall.ware.entity.WareInfoEntity;
import com.bdqn.gulimall.ware.feign.MemberFeignService;
import com.bdqn.gulimall.ware.service.WareInfoService;
import com.bdqn.gulimall.ware.vo.FareVo;
import com.bdqn.gulimall.ware.vo.MemberAddressVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;


@Service("WareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Resource
    MemberFeignService memberFeignService;

    /**
     * 模糊查询
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareInfoEntity> wareInfoEntityQueryWrapper = new QueryWrapper<>();
        String  key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            //id、名字、地址或区域编码是指定的值
            wareInfoEntityQueryWrapper.eq("id",key).or()
                    .like("name",key)
                    .like("address",key)
                    .like("areacode",key);
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wareInfoEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 获取运费
     *
     * @param addrId
     * @return
     */
    @Override
    public FareVo getFare(Long addrId) {
        FareVo fareVo = new FareVo();
        R r = memberFeignService.addrInfo(addrId);
        MemberAddressVo data = r.getData("memberReceiveAddress",new TypeReference<MemberAddressVo>() {
        });
        if(data!=null){
            // TODO: 2022/3/11 0011  运费暂时不做，所以取出手机号最后一位作为运费测试
            String phoneNumber = data.getPhoneNumber();
            String substring = phoneNumber.substring(phoneNumber.length() - 1, phoneNumber.length());
            //运费
            BigDecimal fare = new BigDecimal(substring);
            fareVo.setAddress(data);
            fareVo.setFare(fare);
            return fareVo;
        }
        return null;
    }

}
